package server.core;

import server.Request;
import server.Response;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class WebappsClassLoader extends ClassLoader {

  private String classPath;

  public WebappsClassLoader(String classPath) {
    this.classPath = classPath;
  }

  public WebappsClassLoader() {
  }

  @Override
  public Class<?> loadClass(String name) throws ClassNotFoundException {
    return super.loadClass(name);
  }

  @Override
  protected Class<?> findClass(String name) throws ClassNotFoundException {
    byte[] classData = getData(name);
    if (classData == null) {
      throw new ClassNotFoundException();
    } else {
      System.out.println("当前类加载器:" + this.getClass().getClassLoader().toString());
      return defineClass(name, classData, 0, classData.length);
    }
  }

  private byte[] getData(String name) {
    String path = classPath + File.separatorChar + name.replace('.', File.separatorChar) + ".class";
    try {
      InputStream is = new FileInputStream(path);
      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      byte[] buffer = new byte[2048];
      int num = 0;
      while ((num = is.read(buffer)) != -1) {
        stream.write(buffer, 0, num);
      }
      return stream.toByteArray();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
}
